#include "canthread.h"

VCI_BOARD_INFO vbi;

canThread::canThread(QObject *parent)
    : QObject{parent}
{
    stopped = false;
    deviceType = 4;
    debicIndex = 0;

    //CAN通信波特率为125k bps
//    baundRate = 125;
    debicCom = 0;
    debicCom1 = 0;

//    Timer1.setTimerType(Qt::PreciseTimer);
//    connect(&Timer1,&QTimer::timeout,this,[=]()
//    {
//        Sendradar();
//    });

    timer = startTimer(300);
}

bool canThread::openCan()
{
    int nDeviceType = deviceType; /* USBCAN-2A或USBCAN-2C或CANalyst-II */
    int nDeviceInd = debicIndex; /* 第1个设备 */
    int nCANInd = debicCom; /* 第1个通道 */    
    DWORD dwRel;
//    dwRel = VCI_UsbDeviceReset(nDeviceType, nDeviceInd,nCANInd);
//    dwRel = VCI_UsbDeviceReset(nDeviceType, nDeviceInd,nCANInd+1);
    dwRel = VCI_OpenDevice(nDeviceType, nDeviceInd, nCANInd);
    dwRel = VCI_OpenDevice(nDeviceType, nDeviceInd, nCANInd+1);
    dwRel = VCI_ResetCAN(nDeviceType, nDeviceInd, nCANInd);
    dwRel = VCI_ResetCAN(nDeviceType, nDeviceInd, nCANInd+1);
    if(dwRel != 1)
    {
        emit SIGcanopefai();
        qDebug()<<"open fail";
        return false;
    }
    else
        qDebug()<<"open success";
        emit SIGcansuc("成功启动");
        //emit SIGCanOpen();
    dwRel = VCI_ClearBuffer(nDeviceType, nDeviceInd, nCANInd);
    dwRel = VCI_ClearBuffer(nDeviceType, nDeviceInd, nCANInd+1);
    VCI_INIT_CONFIG vic;
    vic.AccCode=0x80000008;
    vic.AccMask=0xFFFFFFFF;
    vic.Filter=1;
    vic.Mode=0;
    switch (baundRate) {
    case 10:
        vic.Timing0=0x31;
        vic.Timing1=0x1c;
        break;
    case 20:
        vic.Timing0=0x18;
        vic.Timing1=0x1c;
        break;
    case 40:
        vic.Timing0=0x87;
        vic.Timing1=0xff;
        break;
    case 50:
        vic.Timing0=0x09;
        vic.Timing1=0x1c;
        break;
    case 80:
        vic.Timing0=0x83;
        vic.Timing1=0xff;
        break;
    case 100:
        vic.Timing0=0x04;
        vic.Timing1=0x1c;
        break;
    case 125:
        vic.Timing0=0x03;
        vic.Timing1=0x1c;
        break;
    case 200:
        vic.Timing0=0x81;
        vic.Timing1=0xfa;
        break;
    case 250:
        vic.Timing0=0x01;
        vic.Timing1=0x1c;
        break;
    case 400:
        vic.Timing0=0x80;
        vic.Timing1=0xfa;
        break;
    case 500:
        vic.Timing0=0x00;
        vic.Timing1=0x1c;
        break;
    case 666:
        vic.Timing0=0x80;
        vic.Timing1=0xb6;
        break;
    case 800:
        vic.Timing0=0x00;
        vic.Timing1=0x16;
        break;
    case 1000:
        vic.Timing0=0x00;
        vic.Timing1=0x14;
        break;
    case 33:
        vic.Timing0=0x09;
        vic.Timing1=0x6f;
        break;
    case 66:
        vic.Timing0=0x04;
        vic.Timing1=0x6f;
        break;
    case 83:
        vic.Timing0=0x03;
        vic.Timing1=0x6f;
        break;
    default:
        break;
    }
    dwRel = VCI_InitCAN(nDeviceType, nDeviceInd, nCANInd, &vic);
    dwRel = VCI_InitCAN(nDeviceType, nDeviceInd, nCANInd+1, &vic);
    if(dwRel !=1)
    {
        qDebug()<<"init fail";
        emit SIGcanopefai();
        return false;
    }
    else
    {
        qDebug()<<"init success";
        emit SIGCanOpen();
    }



    dwRel = VCI_ReadBoardInfo(nDeviceType, nDeviceInd, &vbi);
    if(dwRel != 1)
    {
//        qDebug()<<"get dev message fail";
        return false;
    }
    else
    {
        qDebug()<<"CAN通道数："<<vbi.can_Num;
        qDebug()<<"硬件版本号:"<<vbi.hw_Version;
        qDebug()<<"接口库版本号："<<vbi.in_Version;
        qDebug()<<"中断号"<<vbi.irq_Num;
    }

    if(VCI_StartCAN(nDeviceType, nDeviceInd, nCANInd) !=1)
    {
//        qDebug()<<"start"<<nCANInd<<"fail:"<<MB_OK<<MB_ICONQUESTION;
        return false;
    }
    else
        qDebug()<<"start"<<nCANInd<<"success:";

    int comid = nCANInd+1;
    if(VCI_StartCAN(nDeviceType, nDeviceInd, comid) !=1)
    {
//        qDebug()<<"start"<<comid<<"fail:"<<MB_OK<<MB_ICONQUESTION;
        return false;
    }
    else
        qDebug()<<"start"<<comid<<"success:";

    stCan();
    return true;

}

void canThread::sleep(unsigned int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void canThread::stopCan()
{
    stopped = true;
    closeCan();
    emit SIGcansuc("雷达断开连接");
    emit SIGCanClose();
}

void canThread::closeCan()
{
    VCI_CloseDevice(deviceType, debicIndex);
    qDebug()<<"closed CAN";
    emit SIGCanClose();
}

void canThread::sendData(int ID, std::vector<int> vec)
{
    DWORD dwRel;
    VCI_CAN_OBJ vco[48];
    vco[0].ID = ID;
    vco[0].RemoteFlag = 0;
    vco[0].ExternFlag = 1;
    vco[0].DataLen = 8;
    for(int j = 0;j<8;j++)
    vco[0].Data[j] = vec[j];
    dwRel = VCI_Transmit(deviceType, debicIndex, debicCom, vco,1);

    QDateTime dateTime= QDateTime::currentDateTime();
    QString time = dateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
    //QString xVal = QString::number(ID,16).toUpper();

    QString xVal =QString("%1").arg(ID, 8, 16, QLatin1Char('0')).toUpper();
    QString data;
    int a;
    for(int i=0;i<8;i++)
    {
        a=vec[i];
        //data = data.append(QString::number(a,16).toUpper());
        data = data.append(QString("%1").arg(a, 2, 16, QLatin1Char('0')));        
    }
    QByteArray data1 = data.toLatin1();
    emit SIGtomain(time+"__"+xVal+"__"+data);
    emit SIGtosqlstosendat(xVal,data1);
    stoSenData(time+"    "+xVal+"    "+data);
    Stop = true;
    //qDebug()<<data;
    emit radstop(Stop);
}

void canThread::stCan()
{
    while(!stopped)
    {
        DWORD dwRel;
        VCI_CAN_OBJ vco[2500];
        dwRel = VCI_Receive(4, 0, 0, vco,500,0);
        if(dwRel > 0)
        {
            dataProcess(vco,dwRel);
            emit SIGtosqlstorecdat(vco,dwRel);
            if(mingling2 == true)
            {
                emit SIGtoSS(vco,dwRel);
            }
        }
        else if(dwRel == -1)
        {
            qDebug()<<"设备不存在或USB掉线";
        }
        sleep(60);
    }
    stopped = false;
}

void canThread::dataProcess(VCI_CAN_OBJ *vci, DWORD dwRel)
{
    QString xVal;
    QDateTime dateTime= QDateTime::currentDateTime();
    QString time = dateTime.toString("yyyy/MM/dd-hh:mm:ss.zzz ");
    unsigned int i;
    int a;

    QString data2;
    for(i = 0;i<dwRel;i++)
    {
        int id = vci[i].ID;
        xVal = QString("%1").arg(id, 8, 16, QLatin1Char('0')).toUpper();
        data2 = 0;
        for(int j = 0;j<8;j++)
        {
           a = vci[i].Data[j];
           data2 = data2.append(QString("%1").arg(a, 2, 16, QLatin1Char('0'))).toUpper();
        }
        emit dataCan(xVal,data2);
        emit SendCan(xVal+"  "+data2);
        stoSenData(time+"   "+xVal+"   "+data2);
        emit dataStart();
    }
   qDebug()<<data2;
}

void canThread::canID(VCI_CAN_OBJ *vci, DWORD dwRel)
{
    QString xVal;
    QDateTime dateTime= QDateTime::currentDateTime();
    QString time = dateTime.toString("yyyy/MM/dd-hh:mm:ss.zzz ");
    unsigned int i;
    int a;

    QString data2;
    for(i = 0;i<dwRel;i++)
    {
        int id = vci[i].ID;
        xVal = QString("%1").arg(id, 8, 16, QLatin1Char('0')).toUpper();
        data2 = 0;
        for(int j = 0;j<8;j++)
        {
           a = vci[i].Data[j];
           data2 = data2.append(QString("%1").arg(a, 2, 16, QLatin1Char('0'))).toUpper();
        }
        //emit dataCan(xVal,data2);
        emit radar_1(xVal+"  "+data2);
    }

}

void canThread::stoRecData(QString data)
{

}

void canThread::stoSenData(QString data)
{

}

void canThread::RceiveKbps(int num)
{
    baundRate = num;
    //qDebug()<<baundRate;
}

void canThread::timerEvent(QTimerEvent *e)
{

}
